<?php
/**
 * Description: 订单物流追踪
 * User: devforma
 * Date: 15/12/25
 * Time: 20:10
 */

class GetExpressInfo implements iController {

    //快递类型-名称
    private $expressNames = array(
        'ZTO'       => '中通快递',
        'YTO'       => '圆通快递',
        'YUNDA'     => '韵达快递',
        'SFEXPRESS' => '顺丰快递',
        'EMS'       => 'ems快递',
        'STO'       => '申通快递',
        'YTEXPRESS' => '运通快递',
    );

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if (empty($queryArgs['product_id']) || empty($queryArgs['product_type']) || validateUser($queryArgs) !== 1) {
            return genOutput(1000);
        }

        switch ($queryArgs['product_type']) {
            case 'live_course':
                $expressInfo = $cmsdb->getRow('SELECT `id`, `express_num`, `express_type` FROM `relation_user_product`
                WHERE `user_id`=:uid AND `product_id`=:pid AND `product_type`="zhiboke" LIMIT 1',
                    array(':uid' => $queryArgs['user_id'], ':pid' => $queryArgs['product_id']));

                if (empty($expressInfo)) {
                    return genOutput(1001);
                }

                //未揽件
                if (empty($expressInfo->express_num) || empty($expressInfo->express_type)) {
                    return genOutput(1, array(
                        'express_num' => '',
                        'express_type' => '',
                        'track_info' => array()
                    ));
                }

                //已览件
                $express = $this->queryExpress($expressInfo->express_num, $expressInfo->express_type);
                return genOutput(1, array(
                    'express_num' => $expressInfo->express_num,
                    'express_type' => $this->expressNames[$expressInfo->express_type],
                    'track_info' => !empty($express) ? $express : array()
                ));

                break;

            default:
                return genOutput(1000);
        }
    }

    /**
     * 查询快递物流信息
     *
     * @param $expressNum
     * @param $expressType
     * @return bool
     */
    private function queryExpress($expressNum, $expressType) {
        $result = httpGet('http://api.jisuapi.com/express/query', array(
            'appkey' => EXPRESS_QUERY_APIKEY,
            'type' => $expressType,
            'number' => $expressNum
        ));

        if (!empty($result) && ($data = json_decode($result)) && $data->status == '0') {
            return $data->result->list;
        }

        return false;
    }
}